<?php

declare(strict_types=1);

namespace app\validate\product;

use think\Validate;

class ProdBulkValidate extends Validate
{
    protected $rule = [
        'seller_org_id' => 'require|integer|gt:0',
        'seller_user_id' => 'integer|gt:0',
        'region_id' => 'integer|gt:0',
        'status' => 'in:0,1,2,3',
        'audit_status' => 'in:0,1,2',
        'publish_time' => 'date',
        'products' => 'require|checkProducts',
    ];

    protected $message = [
        'seller_org_id.require' => '卖家组织不能为空',
        'seller_org_id.integer' => '卖家组织格式不正确',
        'seller_org_id.gt' => '卖家组织格式不正确',
        'seller_user_id.integer' => '卖家用户格式不正确',
        'seller_user_id.gt' => '卖家用户格式不正确',
        'region_id.integer' => '区域格式不正确',
        'region_id.gt' => '区域格式不正确',
        'status.in' => '商品状态不正确',
        'audit_status.in' => '审核状态不正确',
        'publish_time.date' => '发布时间格式不正确',
        'products.require' => '批量商品数据不能为空',
    ];

    protected $scene = [
        'create' => [
            'seller_org_id',
            'seller_user_id',
            'region_id',
            'status',
            'audit_status',
            'publish_time',
            'products',
        ],
    ];

    protected function checkProducts($value, $rule, array $data)
    {
        if (!is_array($value) || $value === []) {
            return '批量商品数据不能为空';
        }

        $base = array_intersect_key($data, array_flip([
            'seller_org_id',
            'seller_user_id',
            'region_id',
            'status',
            'audit_status',
            'publish_time',
        ]));

        foreach ($value as $index => $item) {
            if (!is_array($item)) {
                return sprintf('第 %d 条商品数据格式不正确', $index + 1);
            }

            $payload = array_merge($base, $item);
            $validator = new ProdValidate();
            $validator->scene('create');

            if (!$validator->check($payload)) {
                $error = $validator->getError();
                return sprintf('第 %d 条商品数据校验失败：%s', $index + 1, $error);
            }
        }

        return true;
    }
}
